<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\RegisterRequest;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

/**
 * 用户注册
 * Class RegisterController
 * @package App\Http\Controllers\Api
 */
class RegisterController extends BaseController
{
    public function register(RegisterRequest $registerRequest) {
        try {
            $validated = $registerRequest->validated();
            // print_r($validated);

            // 该表自带 UNIQUE KEY `users_email_unique` (`email`)

            $user = new User();
            $user->name = $validated['name'];
            $user->email = $validated['email'];
            $user->password = Hash::make($validated['name']);
            // 成功，结果是 true。
            $result = $user->save();
            if (!$result) {
                Log::error('用户注册时保存数据库失败: name=' . $user->name . ', email=' . $user->email . ', password=' . $user->password . '.');
                return [
                    'errcode' => 4002,
                    'message' => '注册失败'
                ];
            }

            return [
                'errcode' => 200,
                'message' => '注册成功',
                'data' => $user
            ];
            /*
                password 属性位于 User 模型类的 $hidden 属性中，所以没有返回给客户端。
                {
                    "errcode": 200,
                    "message": "注册成功",
                    "data": {
                        "name": "123",
                        "email": "234@qq.com",
                        "updated_at": "2021-04-28T09:01:38.000000Z",
                        "created_at": "2021-04-28T09:01:38.000000Z",
                        "id": 4
                    }
                }
             */
        } catch (\Exception $exception) {
            Log::error('用户注册时保存数据库异常: name=' . $user->name . ', email=' . $user->email . ', password=' . $user->password . '.');
            Log::error('用户注册时保存数据库异常: exception=' . $exception->getMessage() . '.');
            return [
                'errcode' => 4000,
                'message' => '异常：' . $exception->getMessage()
            ];
        }
    }
}
